package com.jc.oms.shiro;


import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jc.business.rolepermission.RolePermissionBusiness;
import com.jc.business.user.UserBusiness;
import com.jc.business.userrole.UserRoleBusiness;
import com.jc.ds.model.User;
import com.jc.framework.util.WebConstants;


public class UserRealm extends AuthorizingRealm {
	private Logger						logger	= LoggerFactory.getLogger(UserRealm.class);
	@Autowired
	private UserBusiness	 userBusiness;
	
	@Autowired
	private UserRoleBusiness userRoleBusiness;
	
	@Autowired
	private RolePermissionBusiness rolePermissionBusiness;


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Session session = SecurityUtils.getSubject().getSession();
		User cSysUser = (User) session.getAttribute(WebConstants.CURRENT_USER);
		//存储roid列表
		Set<String> shiro_user_roles = userRoleBusiness.getUserRoleListByUserId(cSysUser.getId());
		authorizationInfo.setRoles(shiro_user_roles);
		//存储资源URL列表
		Set<String> shiro_user_permissions = rolePermissionBusiness.getUserPermissionListByUserId(cSysUser.getId());
		authorizationInfo.setStringPermissions(shiro_user_permissions);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo();
		String username = (String) token.getPrincipal();
		try {
			User user = userBusiness.findByUserName(username);
			// 没找到帐号
			if (user == null) { throw new UnknownAccountException("帐号 " + username + " 不存在"); }
			// 帐号锁定
			if (!"normal".equals(user.getIsEnable())) { throw new LockedAccountException("帐号未启用或已删除");}

			authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), // 用户名
					user.getPassWord(), // 密码
					ByteSource.Util.bytes(user.getUserName() + user.getSalt()), // salt=username+salt
					getName() // realm name
			);
	
		} catch (AuthenticationException e) {
			logger.warn("{}{}", username, e.getMessage());
			throw e;
		} catch (Exception e) {
			logger.error("{}{}", username, e.getMessage(), e);
		}
		return authenticationInfo;
	}
	

	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}

	public void clearAllCachedAuthorizationInfo() {
		getAuthorizationCache().clear();
	}

	public void clearAllCachedAuthenticationInfo() {
		getAuthenticationCache().clear();
	}

	public void clearAllCache() {
		clearAllCachedAuthenticationInfo();
		clearAllCachedAuthorizationInfo();
	}
	
}